#!/bin/bash

# DevOps管理平台状态检查脚本

echo "📊 DevOps管理平台状态检查"
echo "================================"

# 检查服务状态
check_service() {
    local service=$1
    local port=$2
    
    if lsof -Pi :$port -sTCP:LISTEN -t >/dev/null 2>&1; then
        echo "✅ $service 正在运行 (端口 $port)"
        return 0
    else
        echo "❌ $service 未运行 (端口 $port)"
        return 1
    fi
}

# 检查进程
check_process() {
    local process_name=$1
    local pattern=$2
    
    if pgrep -f "$pattern" > /dev/null; then
        local pid=$(pgrep -f "$pattern")
        echo "✅ $process_name 正在运行 (PID: $pid)"
        return 0
    else
        echo "❌ $process_name 未运行"
        return 1
    fi
}

echo ""
echo "🔍 基础服务检查："
check_service "MySQL" 3306
check_service "Redis" 6379

echo ""
echo "🔍 应用服务检查："
check_service "Django后端" 8000
check_service "Vue.js前端" 8080

echo ""
echo "🔍 后台进程检查："
check_process "Celery Worker" "celery.*worker"

echo ""
echo "🔍 API连通性测试："

# 测试后端API
if curl -s http://localhost:8000/api/auth/user-suggestions/ > /dev/null 2>&1; then
    echo "✅ 后端API响应正常"
else
    echo "❌ 后端API无响应"
fi

# 测试前端
if curl -s http://localhost:8080/ > /dev/null 2>&1; then
    echo "✅ 前端服务响应正常"
else
    echo "❌ 前端服务无响应"
fi

echo ""
echo "📁 项目文件检查："

# 检查关键文件
files=(
    "devops-backend/manage.py"
    "devops-backend/devops_platform/settings.py"
    "devops-frontend/package.json"
    "devops-frontend/vite.config.js"
    "README.md"
)

for file in "${files[@]}"; do
    if [ -f "$file" ]; then
        echo "✅ $file 存在"
    else
        echo "❌ $file 缺失"
    fi
done

echo ""
echo "💾 数据库连接测试："
cd devops-backend
if source venv/bin/activate && python -c "
import django
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'devops_platform.settings')
django.setup()
from django.db import connection
cursor = connection.cursor()
cursor.execute('SELECT 1')
print('✅ 数据库连接正常')
" 2>/dev/null; then
    :
else
    echo "❌ 数据库连接失败"
fi

cd ..

echo ""
echo "📊 系统资源使用："
echo "CPU使用率: $(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d% -f1)%"
echo "内存使用: $(free | grep Mem | awk '{printf("%.1f%%", $3/$2 * 100.0)}')"
echo "磁盘使用: $(df -h / | tail -1 | awk '{print $5}')"

echo ""
echo "🌐 访问地址："
echo "   前端应用: http://localhost:8080"
echo "   后端API: http://localhost:8000/api"
echo "   Django管理: http://localhost:8000/admin"

echo ""
echo "================================"
echo "状态检查完成 ✨"
